package com.dhy.qigsaw.splash

import android.app.Activity
import android.app.Application
import android.os.Handler
import android.os.Looper
import android.os.Process
import com.dhy.xintent.ActivityKiller
import com.dhy.xintent.simple.SimpleActivityLifecycleCallbacks

object SampleAppKiller {
    private var inited = false
    private var resumeCount = 0
    private var killMe = false
    private val handler by lazy { Handler(Looper.getMainLooper()) }
    fun init(application: Application) {
        if (inited) return
        inited = true
        ActivityKiller.init(application)
        application.registerActivityLifecycleCallbacks(object : SimpleActivityLifecycleCallbacks() {
            override fun onActivityResumed(activity: Activity) {
                resumeCount++
                if (killMe) handler.removeCallbacksAndMessages(null)
            }

            override fun onActivityPaused(activity: Activity) {
                if (resumeCount > 0) resumeCount--
                if (killMe && resumeCount == 0) killMe()
            }
        })
    }

    fun start() {
        println("AppKiller start")
        killMe = true
        killMe()
    }

    private fun killMe() {
        handler.postDelayed({
            if (killMe && resumeCount == 0) {
                println("AppKiller killed")
                ActivityKiller.killAll()
                Process.killProcess(Process.myPid())
            }
        }, 5000)
    }
}